/**
 * Copyright (c) 2009, 2010  Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.penelope.presenterfirst;

import java.util.ArrayList;
import java.util.List;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

/**
 * Junit4 runner for executing Injected Tests. Injected tests have each method annotated with {@link InjectorConfig}
 * annotation which provides the {@link Module}-derived configurations: in this way each method can have a 
 * different configuration.
 */
public class InjectedTestsRunner extends BlockJUnit4ClassRunner {
	
	/**
	 * @param klass
	 * @throws InitializationError
	 */
	public InjectedTestsRunner( Class<?> klass ) throws InitializationError {
		super( klass );
	}

	/* (non-Javadoc)
	 * @see org.junit.runners.BlockJUnit4ClassRunner#methodInvoker(org.junit.runners.model.FrameworkMethod, java.lang.Object)
	 */
	@Override
	protected Statement methodInvoker( FrameworkMethod method, Object test ) {
		InjectorConfig annotation = method.getMethod().getAnnotation( InjectorConfig.class);
		if (annotation != null) {
			List<Module> modules = new ArrayList<Module>();
			for (Class<? extends Module> moduleClass : annotation.value()) {
				try {
					modules.add( moduleClass.newInstance() );
				} catch (Exception e) {
					throw new RuntimeException( String.format( "Could not instantiate module %s: %", moduleClass, e.getMessage() ) );
				} 
			}
			Injector injector = Guice.createInjector( modules );
			injector.injectMembers( test );
		}
		return super.methodInvoker( method, test );
	}
}
